package com.oa.android.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.FujAdapter;
import com.oa.android.adapter.RicTypeAdapter;
import com.oa.android.adapter.WordkTypeAdapter;
import com.oa.android.entry.Fjian;
import com.oa.android.entry.Work;
import com.oa.android.entry.WorkType;
import com.oa.android.utils.ImageUtlis;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.MyGridView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


/**
 * 添加工作
 *
 * @author -zouqh
 */
public class AddWorkActivity extends Activity implements OnClickListener {

    private ImageView close;
    private TextView title, send, workType, addfile, fuj,jies;
    private WebView webView;
    private List<File> listFile;
    private Dialog Jdialog;
    private Dialog typeDialog;
    ProgressDialog dialog;
    private int type;
    private String idStr;
    List<WorkType> workList;
    private String wifid;
    private String content;
    private String personID="";

    private GridView listFj;
    private FujAdapter adapter;
    List<Fjian> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_work_activity);
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        send = (TextView) findViewById(R.id.ritgh_text);
        workType = (TextView) findViewById(R.id.workType);
        webView=(WebView)findViewById(R.id.webView);
        jies= (TextView) findViewById(R.id.jies);
        addfile = (TextView) findViewById(R.id.addFile);
        fuj = (TextView) findViewById(R.id.fuj);
        listFj=(GridView)findViewById(R.id.listFj);
        listFile = new ArrayList<>();
        send.setText("新增");
        title.setText("新建工作");
        list=new ArrayList<>();
        adapter=new FujAdapter(AddWorkActivity.this,list);
        listFj.setAdapter(adapter);
        send.setVisibility(View.VISIBLE);
        getFromType();
        getId();
        close.setOnClickListener(this);
        send.setOnClickListener(this);
        workType.setOnClickListener(this);
        addfile.setOnClickListener(this);
        jies.setOnClickListener(this);
        fuj.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (fuj.getText().length()>0){
                    pointDialog("确定清除附件吗？");
                }

                return false;
            }
        });

        WebSettings webSettings = webView.getSettings();
        webSettings.setSupportZoom(true); // 设置是否支持变焦
        webSettings.setLoadWithOverviewMode(true);// 缩放至屏幕大小
        webSettings.setUseWideViewPort(true);// 将图片调整到是个webview的大小
        webSettings.setDefaultTextEncodingName("utf-8");// 设置编码格式
        webSettings.setLoadsImagesAutomatically(true);// 支持自动加载图片
        webSettings.setJavaScriptEnabled(true);//
        webSettings.setSupportMultipleWindows(true);// 支持多窗口
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);// 支持js打开新窗口
        webSettings.setDomStorageEnabled(true);
        String appCacheDir = this.getApplicationContext()
                .getDir("cache", Context.MODE_PRIVATE).getPath();
        webSettings.setAppCachePath(appCacheDir);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.addJavascriptInterface(new JsInterface(this), "AppView");


        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);
//                webView.loadUrl("javascript: GetContent('"+work.getID()+"')");
            }
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                dialog.dismiss();
            }

        });


        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                Log.i("newProgress---",""+newProgress);
                if (newProgress == 100) {
                    // 网页加载完成
                    dialog.dismiss();
                    JSONObject object=new JSONObject();
                    try {
                        object.put("ID",idStr);
                        object.put("EMPID",UConstants.EmpId);
                        object.put("EMPNAME",UConstants.EmpName);
                        object.put("DEPID",UConstants.DepId);
                        object.put("DEPNAME",UConstants.DepName);
                        object.put("FS","0");
                        object.put("SPID","1");
                        object.put("WKFID",wifid);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    webView.loadUrl("javascript: fun_FormOnLoadF('"+object.toString()+"')");
                } else {
                    // 加载中

                }

            }


        });
        listFj.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("listFj---",position+"---");
                list.remove(position);
                listFile.remove(position);
                adapter.notifyDataSetChanged();
                return false;
            }
        });

    }


    private class JsInterface {
        private Context mContext;

        public JsInterface(Context context) {
            this.mContext=context;
        }

        // 在js中调用window.AndroidWebView.showInfoFromJs(name)，便会触发此方法。
        @JavascriptInterface
        public void showInfoFromJs(String name) {
            content=name;
            handler.sendEmptyMessage(1);

        }
        @JavascriptInterface
        public void cellPhone(String phone) {

            if (null!=phone&&phone.length()>0){
                Uri telUri = Uri.parse("tel:" + phone);
                Intent intent = new Intent(Intent.ACTION_DIAL, telUri);
                startActivity(intent);
            }else{
                Toast.makeText(AddWorkActivity.this,"电话不能为空",Toast.LENGTH_SHORT).show();
            }
        }

    }

    // 在java中调用js代码
    public void sendInfoToJs() {


        //调用js中的函数：(msg)
        JSONObject object=new JSONObject();
        try {
            object.put("ID",idStr);
            object.put("EMPID",UConstants.EmpId);
            object.put("EMPNAME",UConstants.EmpName);
            object.put("DEPID",UConstants.EmpId);
            object.put("DEPNAME",UConstants.EmpName);
            object.put("FS","2");
            object.put("SPID","");
            object.put("WKFID",wifid);
            object.put("NEMPIDS",personID);
            object.put("WKZT","");
            object.put("FORMURL","");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        webView.loadUrl("javascript: showInfoFromJava('"+object.toString()+"')");
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dialog = ProgressDialog.show(AddWorkActivity.this, null, "新增中...", false, false);
            if (null!=listFile&&listFile.size()>0){
                upFj(personID);
            }else {
                addWorkd(personID);
            }
        }
    };


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent intent;
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.ritgh_text:
                String str1 = workType.getText().toString().trim();

                String str4 = personID;
                if (!Util.NoNull(str1)) {
                    Toast.makeText(getApplicationContext(), "请选择工作类型！", Toast.LENGTH_SHORT).show();
                }  else {
                        sendInfoToJs();



                }
                break;

            case R.id.addFile:
                intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);

//                Intent intent1 = new Intent(Intent.ACTION_PICK,
//                        null);
//                intent1.setDataAndType(
//                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
//                        "image/*");
//                startActivityForResult(intent1,
//                        1);
                break;
            case R.id.workType:
                if(null!=workList&&workList.size()>0){
                    showtype();
                }else{
                    Toast.makeText(this, "暂时没有可以选类型", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.jies:
                if (Util.NoNull(wifid)){
                    intent=new Intent(this,NextPersonActivity.class);
                    intent.putExtra("wifid",wifid);
                    intent.putExtra("id",idStr);
                    intent.putExtra("spid","1");
                    startActivityForResult(intent,2);
                }else{
                    Toast.makeText(this, "请选择工作类型", Toast.LENGTH_SHORT).show();
                }

                break;

          default:
                break;
        }
    }

    private Uri mPhotoUri = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续

            if (requestCode==1){
//                String path = getPhotoPath(this, mPhotoUri, data);
//                System.out.println("path----1"+path);
                Uri uri = data.getData();
              String  path= ImageUtlis.getRealPathFromUri(this,uri);
                if (null==path||path.length()<=0){
                    Toast.makeText(this,"获取文件失败",Toast.LENGTH_SHORT).show();
                    return;
                }
                 System.out.println("path----2"+path);
                File file = new File(path);
                listFile.add(file);
                String s = fuj.getText().toString();
                if (s.length() > 0) {
                    fuj.setText(s + "|" + file.getName());
                } else {
                    fuj.setText(file.getName());
                }
                Fjian fjian=new Fjian();
                fjian.setOLDNAME(file.getName());
                list.add(fjian);
                adapter.notifyDataSetChanged();
//                System.out.println("img_path===" + getPhotoPath(this, mPhotoUri, data));
            }else if (requestCode==2){
                if (data != null) {
                    String str = data.getStringExtra("person");
                    personID = data.getStringExtra("personID");
                    System.out.println("personID---"+personID);
                    jies.setText(str);
                }
            }

//
        }
    }

    private String getPhotoPath(Context context, Uri photoUri, Intent data) {
        String photoPath = "";
        ContentResolver cr = context.getContentResolver();
        if (photoUri != null) {
            Cursor cursor = cr.query(photoUri, null, null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                int pathIndex = cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA);
                photoPath = cursor.getString(pathIndex);
                cursor.close();
            }
        } else {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null && !TextUtils.isEmpty(uri.getPath())) {
                    photoPath = uri.getPath();
                    if (!(new File(photoPath).exists())) {
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor actualimagecursor = cr.query(uri, proj, null,
                                null, null);
                        int actualImg = actualimagecursor
                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        actualimagecursor.moveToFirst();
                        if (actualimagecursor != null)
                            photoPath = actualimagecursor.getString(actualImg);
                    }
                }
            }
        }
        return photoPath;
    }


    /**
     * 选择类型
     */
    private void showtype() {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.sb_state_dailog,
                null);
        // 对话框
        typeDialog = new Dialog(this);
        typeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        typeDialog.show();

        typeDialog.setContentView(layout);
        TextView sb=(TextView)layout.findViewById(R.id.name) ;
        sb.setText("请选择工作类型");
        ListView listView = (ListView) layout.findViewById(R.id.statesListView);
        listView.setAdapter(new WordkTypeAdapter(AddWorkActivity.this,workList));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                workType.setText(workList.get(position).getWFNAME());
                wifid=workList.get(position).getWKFID();
                String url=UConstants.DZ+"Samples/"+workList.get(position).getFORMURL()+"l?Empid="+UConstants.EmpId+"&EmpName="+UConstants.EmpName;
               System.out.println(url);
                webView.loadUrl(url);
                typeDialog.dismiss();
                dialog = ProgressDialog.show(AddWorkActivity.this, null, "获取中...", false, false);
            }
        });

    }

    /**
     * 提示
     */
    private void pointDialog(String str) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        dialogTitle.setText(str);
        sure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
                Jdialog.cancel();
                fuj.setText("");
                listFile.clear();


            }
        });
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Jdialog.dismiss();
            }
        });

    }


    //新增
    public void addWorkd(String tof) {
        if (TextUtils.isEmpty(content)||content.length()<80){
            Toast.makeText(AddWorkActivity.this,"网页表单数据不全",Toast.LENGTH_SHORT).show();
            dialog.dismiss();
            return;
        }
        System.out.println("UConstants.ADD_WORK----"+UConstants.ADD_WORK);
        RequestParams params = new RequestParams(UConstants.ADD_WORK);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EMPID", UConstants.EmpId);
        params.addBodyParameter("EMPNAME", UConstants.EmpName);
        params.addBodyParameter("WKFID", wifid);
        params.addBodyParameter("CONTENT", content);
        params.addBodyParameter("NDEMPIDS", tof);
        params.addBodyParameter("ID", idStr);
        System.out.println("content----"+content);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            dialog.dismiss();
                            Toast.makeText(x.app(), "提交成功！", Toast.LENGTH_LONG).show();
                            WorkListActivity.activity.setRef();
                           finish();
                        } else {
                            dialog.dismiss();
                            Toast.makeText(x.app(), ""+object.getString("msg"), Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        dialog.dismiss();
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "提交出错！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }



    //获取ID
    public void getId() {
        Util.printLog("------------UConstants.GET_ID-----", UConstants.GET_ID);

        RequestParams params = new RequestParams(UConstants.GET_ID);
//        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("TNAME", "ERPGZGL");


        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
                        String msg = object.getString("msg");
                        if (success) {
                            idStr=msg;


                        } else {

                            Toast.makeText(x.app(), "获取ID失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {

                        Toast.makeText(x.app(), "获取ID失败！", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }



            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取ID失败！", Toast.LENGTH_LONG).show();

            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");

            }

            @Override
            public void onFinished() {

            }
        });
    }


    //获取表单类型
    public void getFromType() {
        Util.printLog("------------UConstants.GET_ID-----", UConstants.GET_FROM_TYPE);
        dialog = ProgressDialog.show(this, null, "获取中...", false, false);
        RequestParams params = new RequestParams(UConstants.GET_FROM_TYPE);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId", UConstants.EmpId);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    Gson gson = new Gson();
                    Type lt = new TypeToken<List<WorkType>>() {
                    }.getType();
                    workList = gson.fromJson(result.toString(), lt);
                }

                dialog.dismiss();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "新增出错！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    //上传附件
    public void upFj(final String str) {

        RequestParams params = new RequestParams(UConstants.UP_FILI);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("TNAME", "ERPGZGL");
        params.addBodyParameter("XH",idStr );
        Util.printLog("UConstants.UP_FILI------------onSuccess-----", UConstants.UP_FILI);
        for (int i=0;i<listFile.size();i++){
            params.addBodyParameter("FILE",listFile.get(i));
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");

//                        String msg = object.getString("msg");
                        if (success) {
                            addWorkd(str);

                        } else {
                            isShow();
                            Toast.makeText(x.app(), "附件上传失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        isShow();
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(),  "附件上传出错！", Toast.LENGTH_LONG).show();
                isShow();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                isShow();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void isShow(){
        if (null!=dialog&&dialog.isShowing()){
            dialog.dismiss();
        }
    }
}
